<template>
  <div class="chat-list-container app-background">
    <!-- 顶部标题栏 -->
    <header class="chat-list-header">
      <h1>对话</h1>
    </header>

    <!-- 对话列表 -->
    <ul class="chat-list">
      <li
        v-for="(chat, index) in chatList"
        :key="index"
        class="chat-item"
        @click="enterChat(chat)"
      >
        <div class="chat-avatar" :style="{ backgroundColor: chat.bgColor }">
          <i class="chat-icon">{{ chat.icon }}</i>
        </div>
        <div class="chat-info">
          <div class="chat-top">
            <span class="chat-name">{{ chat.title }}</span>
            <span class="chat-time">{{ formatTime(chat.createTime) }}</span>
          </div>
          <p class="chat-preview">{{ chat.preview }}</p>
        </div>
      </li>
    </ul>

    <!-- 修改对话框结构 -->
    <div v-if="showAgentDialog && selectedChat" class="agent-dialog-wrapper">
      <!-- 背景遮罩层 -->
      <div class="agent-dialog-overlay" @click="closeAgentDialog"></div>

      <!-- 对话框内容 -->
      <div class="agent-dialog-fullscreen">
        <div class="dialog-header">
          <div class="agent-header-info">
            <!-- <div class="agent-avatar-header" :style="{ backgroundColor: selectedChat.bgColor }">
              <i class="agent-icon-header">{{ selectedChat.icon }}</i>
            </div> -->
            <h2>{{ selectedChat.title }}</h2>
          </div>
          <!-- 关闭按钮 -->
          <button class="close-button" @click="closeAgentDialog">×</button>
        </div>

        <div class="dialog-content">
          <div v-if="messages.length === 0" class="loading">加载中...</div>
          <div v-else class="messages-container">
            <div
              v-for="(message, index) in messages"
              :key="index"
              :class="['message-container', message.sender]"
            >
              <!-- 显示智能体头像 -->
    <div v-if="message.sender === 'bot'" class="agent-avatar-container">
      <div class="agent-avatar-message" :style="{ backgroundColor: selectedChat.bgColor }">
        <i class="agent-icon-message">{{ selectedChat.icon }}</i>
      </div>
    </div>

    <div :class="['message-bubble', message.sender]">
      <!-- 使用 v-html 渲染包含公式的 HTML 内容 -->
      <div class="message-content" v-html="message.content"></div>

      <!-- 在AI消息气泡中嵌入用户选择界面 -->
      <div v-if="message.showUserSelect" class="embedded-user-select">
        <div class="select-description">{{ message.userSelectDescription }}</div>
        <div class="select-options">
          <button
            v-for="option in message.userSelectOptions"
            :key="option.key"
            @click="handleUserSelect(option.value, index)"
            :class="['select-option-button', { 'selected': option.selected }]"
          >
            {{ option.value }}
          </button>
        </div>
      </div>

      <div class="message-time">{{ message.time }}</div>
    </div>
  </div>
</div>


        </div>

        <!-- 在 HomeView.vue 的 dialog-input 部分添加语音输入按钮 -->
        <div class="dialog-input">
          <input
            v-model="userInput"
            @keyup.enter="sendMessage"
            placeholder="输入消息..."
            :disabled="sending"
            lang="zh-CN"
            ref="messageInput"
          />
          <!-- 添加语音输入按钮 -->
          <button
            @click="startSpeechInput"
            class="speech-button"
            :disabled="sending || !isSpeechSupported"
            :class="{ listening: isListening }"
            type="button"
          >
            <span class="mic-icon" :class="{ listening: isListening }"></span>
          </button>
          <button @click="sendMessage" :disabled="sending">
            {{ sending ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
    </div>

<!-- 修改底部导航栏 -->
<footer class="chat-list-footer">
  <div class="nav-item" :class="{ active: $route.name === 'index' }" @click="navigateTo('/')">
    <i class="nav-icon home-icon"></i>
    <span>首页</span>
  </div>
  <div class="nav-item" :class="{ active: $route.name === 'home' || $route.name === 'mobiles' }" @click="navigateTo('/mobiles')">
    <i class="nav-icon message-icon"></i>
    <span>对话</span>
  </div>
  <div class="nav-item" :class="{ active: $route.name === 'discover' }" @click="navigateTo('/discover')">
    <i class="nav-icon discover-icon"></i>
    <span>发现</span>
  </div>
</footer>

  </div>
</template>

<script>
import { generateSecureRandomString } from '@/utils/crypto.js';
import { streamFetch, SseResponseEventEnum } from '@/utils/streamFetch.js';
import { getToken, getXauatLoginToken, setToken,clearToken } from '@/utils/auth.js'; // 添加这行


export default {
   name: 'HomeView',
  data() {
    return {
      chatList: [],
      defaultIcon: "💬",
      defaultBgColor: "#e3f2fd",
      showAgentDialog: false, // 控制对话框显示
      selectedChat: null,
      messages: [],
      userInput: '',
      sending: false,
      sessionId: null,
      abortController: null,
      // 暖色调颜色数组
      warmColors: [
        '#FFB3BA', // 浅粉红
        '#FFDFBA', // 淡橙色
        '#FFFFBA', // 淡黄色
        '#BAFFC9', // 淡绿色
        '#BAE1FF', // 淡蓝色
        '#E1BAFF', // 淡紫色
        '#FFC9B3', // 浅珊瑚色
      ],
      // 语音识别相关
    isSpeechSupported: false,
    isListening: false,
    speechRecognition: null,
      showUserSelect: false,  // 是否显示用户选择界面
    userSelectDescription: '',  // 选择描述
    userSelectOptions: [],  // 选择选项
    interactiveData: null,  // 保存交互数据
    };
  },

async mounted() {
  // 只执行初始化逻辑，不再尝试获取token
  this.fetchChatHistory()
  this.checkSpeechRecognitionSupport()
},
  methods: {

renderMarkdown(text) {
  // 如果 text 不是字符串，先转换为字符串
  if (typeof text !== 'string') {
    if (text === null || text === undefined) {
      return '';
    }
    text = JSON.stringify(text);
  }

  if (!text) return '';

  // 处理JSON包装的文本内容（如历史记录）
  let processedText = text;

  try {
    // 检查是否是JSON格式的文本
    if (typeof text === 'string') {
      const trimmedText = text.trim();
      if (trimmedText.startsWith('[{') && trimmedText.endsWith('}]')) {
        // 先尝试修复可能的JSON格式问题
        let fixedJson = trimmedText;

        // 尝试解析，如果失败则进行修复
        try {
          JSON.parse(trimmedText);
        } catch (parseError) {
          // 如果解析失败，尝试修复常见的JSON问题
          // 例如修复未转义的引号
          fixedJson = trimmedText.replace(/([^\\])"/g, '$1\\"');
          // 确保开头和结尾正确
          if (!fixedJson.startsWith('[{')) {
            fixedJson = '[{' + fixedJson.substring(2);
          }
          if (!fixedJson.endsWith('}]')) {
            fixedJson = fixedJson.substring(0, fixedJson.length - 2) + '}]';
          }
        }

        const parsed = JSON.parse(fixedJson);
        // 确保解析成功且有内容
        if (Array.isArray(parsed) && parsed.length > 0 &&
            parsed[0].hasOwnProperty('text') &&
            parsed[0].text &&
            parsed[0].text.hasOwnProperty('content')) {
          processedText = parsed[0].text.content;
        }
      }
    }
  } catch (e) {
    // 如果解析失败，尝试使用正则表达式提取内容
    try {
      const contentMatch = text.match(/"content":"((?:[^"\\]|\\.)*)"/);
      if (contentMatch && contentMatch[1]) {
        // 解码转义字符
        processedText = contentMatch[1]
          .replace(/\\n/g, '\n')
          .replace(/\\t/g, '\t')
          .replace(/\\r/g, '\r')
          .replace(/\\(.)/g, '$1');
      }
    } catch (fallbackError) {
      // 如果所有方法都失败，使用原始文本
      console.warn('解析JSON格式文本失败，使用原始文本:', e);
      processedText = text;
    }
  }

  // 确保 processedText 是字符串
  if (typeof processedText !== 'string') {
    processedText = String(processedText);
  }

  // 转义HTML特殊字符
  let result = processedText
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");

  // 处理模块标题，添加加粗效果并确保换行
  result = result.replace(/【(.*?)】/g, '<strong>【$1】</strong><br>');

  // 处理LaTeX数学公式（行内公式）
  result = result.replace(/\$([^$]+)\$/g, '<span class="math-inline">\\( $1 \\)</span>');

  // 处理LaTeX块级公式
  result = result.replace(/\$\$([\s\S]*?)\$\$/g, '<div class="math-block">\\[ $1 \\]</div>');

  // 处理水平分隔线
  result = result.replace(/(^|\n)---(?=\n|$)/g, '$1<hr>');

  // 处理引用块
  result = result.replace(/(^|\n)> \s*(.*?)(?=\n|$)/g, '$1<blockquote>$2</blockquote>');

  // 处理标题（规范化层级）
  result = result.replace(/(^|\n)######\s+(.*?)(?=\n|$)/g, '$1<h6>$2</h6>');
  result = result.replace(/(^|\n)#####\s+(.*?)(?=\n|$)/g, '$1<h5>$2</h5>');
  result = result.replace(/(^|\n)####\s+(.*?)(?=\n|$)/g, '$1<h4>$2</h4>');
  result = result.replace(/(^|\n)###\s+(.*?)(?=\n|$)/g, '$1<h3>$2</h3>');
  result = result.replace(/(^|\n)##\s+(.*?)(?=\n|$)/g, '$1<h2>$2</h2>');
  result = result.replace(/(^|\n)#\s+(.*?)(?=\n|$)/g, '$1<h1>$2</h1>');

  // 处理粗体
  result = result.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

  // 处理斜体
  result = result.replace(/(?<!\*)\*([^*]+?)\*(?!\*)/g, '<em>$1</em>');

  // 处理行内代码
  result = result.replace(/`([^`]+?)`/g, '<code>$1</code>');

  // 处理规范化链接格式 [text](url)
  result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');

  // 处理未格式化的链接（括号格式）（https://example.com）
  result = result.replace(/（(https?:\/\/[^)]+)）/g, '<a href="$1" target="_blank" rel="noopener">下载Word文档</a>');

  // 处理纯URL链接（以http或https开头的独立链接）
  result = result.replace(/(^|\s)(https?:\/\/[^\s<>"{}|\\^`\[\]]+)/g, '$1<a href="$2" target="_blank" rel="noopener">$2</a>');

  // 处理特殊下载链接格式
  result = result.replace(/\[单元出题：([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">单元出题：$1（下载Word文档）</a>');

  // 处理简单的文件下载链接提示
  result = result.replace(/(下载地址|下载链接)[:：]\s*(https?:\/\/[^\s<>"{}|\\^`\[\]]+)/gi, '$1: <a href="$2" target="_blank" rel="noopener">$2</a>');

  // 特别处理"点击下载：URL"格式
  result = result.replace(/点击下载[:：]\s*(https?:\/\/[^\s<>"{}|\\^`\[\]]+)/gi, '点击下载: <a href="$1" target="_blank" rel="noopener">$1</a>');

  // 处理换行 - 与 DiscoverView.vue 保持一致，不包装在 <p> 标签中
  result = result.replace(/\n/g, '<br>');

  return result;
},



    // 添加一个新的方法用于初始化聊天
  async fetchChatHistory() {
    try {
    const token = getToken(); // 获取动态token
    const response = await fetch('/huayun-ai/client/chat/page', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        size: 20,
        current: 1,
        keyword: ""
        })
      });

      const result = await response.json();
      if (result.success) {
        // 注意这里添加了 (record, index) 参数
        this.chatList = result.data.records.map((record, index) => ({
          ...record,
          icon: this.defaultIcon,
          // 为每个聊天项分配颜色，确保相邻项颜色不同
          bgColor: this.warmColors[index % this.warmColors.length],
          //preview: "",
          // 确保appId存在
          appId: record.appId || record.id
        }));
      }
    } catch (error) {
      // 检查是否是认证错误
    if (error.message.includes('401') || error.message.includes('未授权') || error.message.includes('令牌已失效')) {
      console.log('Token失效，尝试重新认证');
      // 清除本地token
      clearToken();

      // 检查是否是西安建筑科技大学域名
      const domain = window.location.hostname;
      if (domain === 'aimobiles.xauat.edu.cn') {
        // 重定向到认证服务器
        const authUrl = 'https://authserver.xauat.edu.cn/authserver/oauth2.0/authorize?response_type=code&client_id=1427671951913222144&redirect_uri=https://aimobiles.xauat.edu.cn';
        window.location.href = authUrl;
        return;
      }
    }

    console.error('获取聊天历史失败:', error);
  }
},

  formatTime(timeString) {
    if (!timeString) return '';

    const date = new Date(timeString);
    const now = new Date();

    // 检查日期是否有效
    if (isNaN(date.getTime())) return '';

    // 设置为同一天的开始时间进行比较
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());

    // 计算日期差
    const timeDiff = today.getTime() - messageDate.getTime();
    const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

    if (messageDate.getTime() === today.getTime()) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (messageDate.getTime() === yesterday.getTime()) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (daysDiff < 7) {
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return `${weekdays[date.getDay()]} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  },


   // 添加一个新的方法用于页面加载时的默认初始化
    async initDefaultChat() {
      try {
        // 获取动态token
        const token = getToken();
        // 发送初始化请求，不依赖特定的聊天项
        const initResponse = await fetch('/huayun-ai/client/chat/new/init', {
          method: 'POST',
          headers: {
            'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
            'Content-Type': 'application/json',
            'Origin': 'https://owner-b.xauat.edu.cn',
            'Referer': 'https://owner-b.xauat.edu.cn/home'
          },
          credentials: 'include',
          body: JSON.stringify({
            tenantAppId: "", // 可以为空或使用默认值
            chatId: ""
          })
        });

        const initData = await initResponse.json();
        if (initData.success) {
          console.log('默认初始化成功:', initData);
          this.sessionId = initData.data?.chatId;

          // 如果有默认消息或需要处理的数据，可以在这里处理
          // 例如设置一些默认的欢迎消息等
        } else {
          console.error('默认初始化失败:', initData.msg);
        }
      } catch (error) {
        console.error('默认初始化请求失败:', error);
      }
    },
  async enterChat(chat) {
  console.log(`进入与${chat.title}的对话`);

  // 设置选中的聊天
  this.selectedChat = chat;
  this.messages = [];

  // 设置显示对话框
  this.showAgentDialog = true;

  // 调用初始化接口
  try {
    // 获取当前聊天的场景ID
    let sceneId = chat.sceneId || 34596;
    // 获取动态token
    const token = getToken();

    // 首先调用 app/form/detail 接口
    try {
      const formDetailResponse = await fetch('/huayun-ai/client/app/form/detail', {
        method: 'POST',
        headers: {
          'Accept': 'application/json, text/plain, */*',
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
          'Content-Type': 'application/json',
          'Origin': 'https://owner-b.xauat.edu.cn',
          'Referer': `https://owner-b.xauat.edu.cn/home?appId=${chat.tenantAppId || chat.appId}&chatId=${chat.chatId}&sceneId=${sceneId}&isBack=1`
        },
        credentials: 'include',
        body: JSON.stringify({
          id: parseInt(chat.tenantAppId || chat.appId) // 确保id是数字类型
        })
      });

      const formDetailResult = await formDetailResponse.json();
      console.log('表单详情接口返回结果:', formDetailResult);
    } catch (formError) {
      console.warn('表单详情接口调用失败:', formError);
    }

    // 直接调用初始化接口，使用聊天项中的参数
    const initResponse = await fetch('/huayun-ai/client/chat/new/init', {
      method: 'POST',
      headers: {
        //身份
         'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
        'Origin': 'https://owner-b.xauat.edu.cn',
        'Referer': `https://owner-b.xauat.edu.cn/home?appId=${chat.tenantAppId || chat.appId}&chatId=${chat.chatId}&sceneId=${sceneId}&isBack=1`
      },
      credentials: 'include',
      body: JSON.stringify({
        tenantAppId: chat.tenantAppId || chat.appId,
        chatId: chat.chatId || ""
      })
    });

    const initData = await initResponse.json();
    if (initData.success) {
      console.log('初始化成功:', initData);
      this.sessionId = initData.data?.chatId;

      if (initData.data.history && Array.isArray(initData.data.history)) {
  const historyMessages = initData.data.history
    .reduce((acc, record) => {
      // 检查是否有 historyPreview 字段
      if (record.responseData && Array.isArray(record.responseData)) {
        // 查找包含 historyPreview 的 AI 响应数据
        const chatNodeData = record.responseData.find(item =>
          item.moduleType === 'chatNode' &&
          item.historyPreview &&
          Array.isArray(item.historyPreview)
        );

        if (chatNodeData && chatNodeData.historyPreview) {
          // 从 historyPreview 中提取 Human 和 AI 的对话
          const previewMessages = chatNodeData.historyPreview
            .filter(preview => {
              // 只提取 AI 的回复，避免重复提取用户消息
              return preview.obj === 'AI';
            })
            .map(preview => ({
              sender: 'bot',
              content: this.renderMarkdown(preview.value) || '消息内容为空',
              time: new Date(preview.time || Date.now()).toLocaleTimeString()
            }));

          acc.push(...previewMessages);
          return acc; // 关键：处理完 historyPreview 后直接返回，避免重复处理
        }
      }

      // 保持原有逻辑作为备选方案
      let content = '';
      let sender = 'bot';

      // 判断消息发送者
      if (record.obj === 'Human') {
        sender = 'user';
        // 从 value 字段获取用户消息
        if (Array.isArray(record.value)) {
          content = record.value
            .filter(item => item.type === 'text' && item.text && item.text.content)
            .map(item => item.text.content)
            .join('\n');
        } else if (typeof record.value === 'string') {
          content = record.value;
        }
      } else {
        // 优先从 responseData 字段获取 AI 回复消息
        if (record.responseData) {
          try {
            const responseData = JSON.parse(record.responseData);
            if (Array.isArray(responseData)) {
              content = responseData
                .filter(item => item.type === 'text' && item.text && item.text.content)
                .map(item => item.text.content)
                .join('\n');
            } else if (typeof responseData === 'string') {
              content = responseData;
            }
          } catch (e) {
            // 如果解析失败，直接使用 responseData
            content = record.responseData;
          }
        } else if (record.valueJson) {
          // 兼容旧的 valueJson 字段
          try {
            const valueJson = JSON.parse(record.valueJson);
            if (Array.isArray(valueJson)) {
              content = valueJson
                .filter(item => item.type === 'text' && item.text && item.text.content)
                .map(item => item.text.content)
                .join('\n');
            } else if (typeof valueJson === 'string') {
              content = valueJson;
            }
          } catch (e) {
            content = record.valueJson;
          }
        }
      }

      const message = {
        sender: sender,
        content: this.renderMarkdown(content) || '消息内容为空',
        time: new Date(record.createTime || Date.now()).toLocaleTimeString()
      };

      // 只添加非空内容的消息
      if (message.content && message.content.trim() !== '') {
        acc.push(message);
      }

      return acc;
    }, [])
    .filter((record, index, self) => {
      // 更严格的去重逻辑：通过内容、发送者和时间戳的组合来去重
      const currentIndex = self.findIndex((item) =>
        item.content === record.content &&
        item.sender === record.sender
      );
      return currentIndex === index;
    });

  this.messages = historyMessages;
}
    } else {
      console.error('初始化失败:', initData.msg);
      this.messages.push({
        sender: 'bot',
        content: '初始化失败，请稍后重试',
        time: new Date().toLocaleTimeString()
      });
    }
  } catch (error) {
    console.error('初始化请求失败:', error);
    this.messages.push({
      sender: 'bot',
      content: '加载对话失败，请稍后重试',
      time: new Date().toLocaleTimeString()
    });
  }

  // 在设置完消息后触发 MathJax 渲染
  this.$nextTick(() => {
    if (window.MathJax) {
      window.MathJax.typesetPromise();
    }
  });
},
// 用于初始化聊天
async initChat(chat) {
      try {
        // 获取当前聊天的场景ID
        let sceneId = chat.sceneId || 34596;

        // 获取动态token
        const token = getToken();

        // 首先调用 app/form/detail 接口
        try {
          const formDetailResponse = await fetch('/huayun-ai/client/app/form/detail', {
            method: 'POST',
            headers: {
              'Accept': 'application/json, text/plain, */*',
              'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
              'Content-Type': 'application/json',
              'Origin': 'https://owner-b.xauat.edu.cn',
              'Referer': `https://owner-b.xauat.edu.cn/home?appId=${chat.tenantAppId || chat.appId}&chatId=${chat.chatId}&sceneId=${sceneId}&isBack=1`
            },
            credentials: 'include',
            body: JSON.stringify({
              id: parseInt(chat.tenantAppId || chat.appId) // 确保id是数字类型
            })
          });

          const formDetailResult = await formDetailResponse.json();
          console.log('表单详情接口返回结果:', formDetailResult);
        } catch (formError) {
          console.warn('表单详情接口调用失败:', formError);
        }

        const initResponse = await fetch('/huayun-ai/client/chat/new/init', {
          method: 'POST',
          headers: {
            'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
            'Content-Type': 'application/json',
            'Origin': 'https://owner-b.xauat.edu.cn',
            'Referer': `https://owner-b.xauat.edu.cn/home?appId=${chat.tenantAppId || chat.appId}&chatId=${chat.chatId}&sceneId=${sceneId}&isBack=1`
          },
          credentials: 'include',
          body: JSON.stringify({
            tenantAppId: chat.tenantAppId || chat.appId,
            chatId: chat.chatId || ""
          })
        });

        const initData = await initResponse.json();
        if (initData.success) {
          console.log('初始化成功:', initData);
          this.sessionId = initData.data?.chatId;

        if (initData.data.history && Array.isArray(initData.data.history)) {
  const historyMessages = initData.data.history
    .reduce((acc, record) => {
      // 检查是否有 historyPreview 字段
      if (record.responseData && Array.isArray(record.responseData)) {
        // 查找包含 historyPreview 的 AI 响应数据
        const chatNodeData = record.responseData.find(item =>
          item.moduleType === 'chatNode' &&
          item.historyPreview &&
          Array.isArray(item.historyPreview)
        );

        if (chatNodeData && chatNodeData.historyPreview) {
          // 从 historyPreview 中提取 Human 和 AI 的对话
          const previewMessages = chatNodeData.historyPreview
            .filter(preview => {
              // 只提取 AI 的回复，避免重复提取用户消息
              return preview.obj === 'AI' || preview.obj === 'System';
            })
            .map(preview => ({
              sender: 'bot',
              content: this.renderMarkdown(preview.value) || '消息内容为空',
              time: new Date(preview.time || Date.now()).toLocaleTimeString()
            }));

          acc.push(...previewMessages);
          return acc; // 关键：处理完 historyPreview 后直接返回，避免重复处理
        }
      }

      // 保持原有逻辑作为备选方案
      let content = '';
      let sender = 'bot';

      // 判断消息发送者
      if (record.obj === 'Human') {
        sender = 'user';
        // 从 value 字段获取用户消息
        if (Array.isArray(record.value)) {
          content = record.value
            .filter(item => item.type === 'text' && item.text && item.text.content)
            .map(item => item.text.content)
            .join('\n');
        } else if (typeof record.value === 'string') {
          content = record.value;
        }
      } else {
        // 从 value 字段获取 AI 回复消息
        if (Array.isArray(record.value)) {
          content = record.value
            .filter(item => item.type === 'text' && item.text && item.text.content)
            .map(item => item.text.content)
            .join('\n');
        } else if (typeof record.value === 'string') {
          content = record.value;
        } else if (record.valueJson) {
          // 兼容旧的 valueJson 字段
          try {
            const valueJson = JSON.parse(record.valueJson);
            if (Array.isArray(valueJson)) {
              content = valueJson
                .filter(item => item.type === 'text' && item.text && item.text.content)
                .map(item => item.text.content)
                .join('\n');
            } else if (typeof valueJson === 'string') {
              content = valueJson;
            }
          } catch (e) {
            content = record.valueJson;
          }
        }
      }

      const message = {
        sender: sender,
        content: this.renderMarkdown(content) || '消息内容为空',
        time: new Date(record.createTime || Date.now()).toLocaleTimeString()
      };

      // 只添加非空内容的消息
      if (message.content && message.content.trim() !== '') {
        acc.push(message);
      }

      return acc;
    }, [])
    .filter((record, index, self) => {
      // 更严格的去重逻辑：通过内容、发送者和时间戳的组合来去重
      const currentIndex = self.findIndex((item) =>
        item.content === record.content &&
        item.sender === record.sender
      );
      return currentIndex === index;
    });

  this.messages = historyMessages;
          }

          // 在设置完消息后触发 MathJax 渲染
          this.$nextTick(() => {
            if (window.MathJax) {
              window.MathJax.typesetPromise();
            }
          });

          return true;
        } else {
          console.error('初始化失败:', initData.msg);
          return false;
        }
      } catch (error) {
        console.error('初始化请求失败:', error);
        return false;
      }
    },

/**
   * 处理用户选择
   */
  // 修改 handleUserSelect 方法
handleUserSelect(selectedValue, messageIndex) {
  console.log('用户选择:', selectedValue);

  // 更新消息中的选项状态
  if (messageIndex !== undefined && this.messages[messageIndex]) {
    const message = this.messages[messageIndex];
    if (message.userSelectOptions) {
      // 标记选中的选项
      message.userSelectOptions = message.userSelectOptions.map(option => ({
        ...option,
        selected: option.value === selectedValue
      }));
    }
  }

  // 发送用户选择作为进一步的输入 - 使用普通的sendMessage方法
  this.userInput = selectedValue;
  this.sendMessage();
},

  /**
   * 发送用户选择
   */
  // 修改 sendUserSelect 方法，将其改为 sendMessage 的逻辑
async sendUserSelect(selectedValue) {
  console.log('发送用户选择:', selectedValue);

  // 直接调用 sendMessage 方法处理用户选择
  this.userInput = selectedValue;
  await this.sendMessage();
},

  /**
   * 处理交互事件
   */
  handleInteractiveEvent(event) {
  console.log('处理交互事件:', event);

  // 支持多种事件结构
  let interactiveData = null;

  if (event.interactive) {
    interactiveData = event.interactive;
  } else if (event.type && event.params) {
    interactiveData = event;
  } else {
    console.warn('收到的事件格式不符合预期:', event);
    return;
  }

  // 处理 userSelect 类型的交互
  if (interactiveData.type === 'userSelect' || interactiveData.type === 'select') {
    // 保存交互数据
    this.interactiveData = interactiveData;

    // 在最后一条AI消息中添加选择界面
    if (this.messages.length > 0) {
      const lastMessage = this.messages[this.messages.length - 1];
      if (lastMessage.sender === 'bot') {
        // 初始化选项，添加selected属性
        const optionsWithSelection = (interactiveData.params?.userSelectOptions || interactiveData.params?.options || [])
          .map(option => ({
            ...option,
            selected: false
          }));

        lastMessage.showUserSelect = true;
        lastMessage.userSelectDescription = interactiveData.params?.description || '';
        lastMessage.userSelectOptions = optionsWithSelection;
      }
    }
  } else {
    console.log('未识别的交互事件类型:', interactiveData.type, interactiveData);
  }
},
/**
   * 发送消息方法 - 使用streamFetch处理流式响应
   */
  /**
   * 发送消息方法 - 完全对齐PC端流程
   */
  // 修改 sendMessage 方法
async sendMessage() {
  if (!this.userInput.trim() || this.sending) return;

  // 如果还没有 sessionId，则生成一个新的
  if (!this.sessionId) {
    this.sessionId = generateSecureRandomString();
    console.log('生成新的 sessionId:', this.sessionId);
  }

  const message = {
    sender: 'user',
    content: this.userInput,
    time: new Date().toLocaleTimeString()
  };

  this.messages.push(message);
  const userMessage = this.userInput;
  this.userInput = '';
  this.sending = true;

  // 创建机器人消息 - 显示"正在输入中..."
  let botMessage = {
    sender: 'bot',
    content: '正在输入中...',
    time: new Date().toLocaleTimeString()
  };
  this.messages.push(botMessage);

  // 用于存储AI响应内容和流程数据
  let responseText = '';
  let responseData = [];
  let isFirstMessage = this.messages.filter(msg => msg.sender === 'user').length === 1;

  // 生成responseChatItemId（与PC端保持一致）
  this.currentResponseChatItemId = generateSecureRandomString();

  try {
    this.abortController = new AbortController();

    // 构建与PC端一致的请求数据
    const requestData = {
      single: false,
      ocrFileKey: null,
      chatAppId: this.selectedChat.tenantAppId || this.selectedChat.appId,
      value: `[{"type":"text","text":{"content":"${userMessage}"}}]`,
      content: userMessage,
      fileKeys: [],
      messages: [{
        role: "user",
        content: userMessage
      }],
      responseChatItemId: this.currentResponseChatItemId,
      variables: {
        cTime: new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-')
      },
      tenantAppId: this.selectedChat.tenantAppId || this.selectedChat.appId,
      chatId: this.sessionId,
      rawParseResult: null
    };

    console.log('发送请求数据:', requestData);

    // 使用streamFetch处理流式响应
    const { responseText: finalResponseText, responseData: finalResponseData, isInteractive } = await streamFetch({
      url: '/huayun-ai/client/chat/completions',
      data: requestData,
      onMessage: (event) => {
        // 处理不同类型的事件
        if (event.event === SseResponseEventEnum.answer ||
            event.event === SseResponseEventEnum.fastAnswer) {
          if (event.text) {
            // 如果是第一个字符，清除"正在输入中..."提示
            if (responseText === '') {
              botMessage.content = '';
            }

            botMessage.content += event.text;
            this.$forceUpdate();
          }
        } else if (event.event === SseResponseEventEnum.answerDone) {
          console.log('回答完成');
        } else if (event.event === SseResponseEventEnum.toolCall) {
          console.log('工具调用:', event);
        } else if (event.event === SseResponseEventEnum.flowNodeStatus) {
          console.log('流程节点状态:', event);
        } else if (event.event === SseResponseEventEnum.interactive) {
          // 处理交互事件
          console.log('交互事件:', event);
          this.handleInteractiveEvent(event);
        } else if (event.event === SseResponseEventEnum.flowResponses) {
          if (event.data) {
            if (Array.isArray(event.data)) {
              responseData.push(...event.data);
            } else {
              responseData.push(event.data);
            }
          }
          console.log('流程响应数据:', event.data);
        }
      },
      abortCtrl: this.abortController
    });

    // 聊天完成后的处理逻辑（完全对齐PC端流程）
    console.log('聊天完成，开始后处理...', {
      responseText: finalResponseText,
      responseData: finalResponseData,
      isInteractive: isInteractive
    });

    // 使用最终的响应数据
    const finalResponse = finalResponseText || responseText;
    const finalData = finalResponseData || responseData;

    // 1. 如果是新对话，处理新对话完成流程
    if (isFirstMessage && finalResponse.trim()) {
      await this.handleNewChatCompletion(userMessage, finalResponse);
    } else if (finalResponse.trim()) {
      // 2. 如果是现有对话，更新聊天历史
      await this.updateExistingChatHistory();
    }

    // 3. 更新聊天项详情（包含responseData）
    if (finalResponse.trim()) {
      await this.updateChatItemWithResponseData(finalResponse, finalData);
    }

  } catch (error) {
    console.error('发送消息失败:', error);
    if (error.name === 'AbortError') {
      botMessage.content = '请求已取消';
    } else {
      botMessage.content = error.message || '抱歉，发生了错误，请稍后重试。';
    }
    this.$forceUpdate();
  } finally {
    this.sending = false;
    this.abortController = null;

    // 触发 MathJax 渲染
    this.$nextTick(() => {
      if (window.MathJax) {
        window.MathJax.typesetPromise();
      }
    });
  }
},

  navigateTo(path) {
  this.$router.push(path);
},

  /**
   * 处理新对话完成后的流程（与PC端保持一致）
   * @param {string} userMessage - 用户消息
   * @param {string} responseText - AI回复内容
   */
  async handleNewChatCompletion(userMessage, responseText) {
    try {
      // 1. 生成聊天标题（使用PC端的/client/chat/once接口）
      await this.generateChatTitleWithAPI(userMessage, responseText);

      // 2. 更新聊天历史记录
      await this.updateChatHistoryRecord();

    } catch (error) {
      console.error('新对话完成处理失败:', error);
      this.chatTitle = '新对话';
    }
  },

  /**
   * 更新现有聊天历史记录
   */
  async updateExistingChatHistory() {
    try {
      await this.updateChatHistoryRecord();
    } catch (error) {
      console.error('更新现有聊天历史记录失败:', error);
    }
  },

  /**
   * 更新聊天历史记录（与PC端chatUpdate保持一致）
   */
      async updateChatHistoryRecord() {
        try {
          const token = getToken(); // 获取动态token
          const response = await fetch('/huayun-ai/client/chat/update', {
            method: 'POST',
            headers: {
              'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
              'Content-Type': 'application/json',
            },
        credentials: 'include',
        body: JSON.stringify({
          chatId: this.sessionId,
          title: this.chatTitle || '新对话',
          tenantAppId: this.selectedChat.tenantAppId || this.selectedChat.appId
        })
      });

      const result = await response.json();
      console.log('聊天历史记录更新结果:', result);

      if (result.success) {
        console.log('聊天历史记录更新成功');
      } else {
        console.warn('聊天历史记录更新失败:', result.msg);
      }
    } catch (error) {
      console.error('聊天历史记录更新出错:', error);
    }
  },

  /**
   * 更新聊天项详情（包含responseData）
   * @param {string} responseText - AI回复内容
   * @param {Array} responseData - 响应数据
   */
  async updateChatItemWithResponseData(responseText, responseData) {
    try {
      if (!responseText || !this.sessionId || !this.currentResponseChatItemId) {
        console.warn('缺少必要参数，跳过聊天项更新');
        return;
      }

      const token = getToken(); // 获取动态token
      const valueContent = `[{"type":"text","text":{"content":"${responseText.replace(/"/g, '\\"').replace(/\n/g, '\\n')}"}}]`;

      const payload = {
        dataId: this.currentResponseChatItemId,
        value: valueContent,
        content: responseText,
        responseData: JSON.stringify(responseData) // 与PC端保持一致，转换为字符串
      };

      console.log('更新聊天项的payload:', payload);

      const response = await fetch('/huayun-ai/client/chat/item/update', {
        method: 'POST',
        headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
      },
        credentials: 'include',
        body: JSON.stringify(payload)
      });

      const result = await response.json();
      console.log('聊天项更新结果:', result);

      if (result.success) {
        console.log('聊天项更新成功');
      } else {
        console.warn('聊天项更新失败:', result.msg);
      }
    } catch (error) {
      console.error('聊天项更新出错:', error);
    }
  },

  /**
   * 使用API生成聊天标题（按照PC端流程）
   * @param {string} userMessage - 用户消息
   * @param {string} aiResponse - AI响应内容
   * @deprecated 请使用handleNewChatCompletion方法
   */
  async generateChatTitleWithAPI(userMessage, aiResponse) {
    try {
      console.log('开始生成聊天标题...');

      await streamFetch({
        url: '/huayun-ai/client/chat/once',
        data: {
          chatAppId: this.selectedChat.tenantAppId || this.selectedChat.appId,
          content: `请为以下对话生成一个简洁的标题（不超过10个字）：\n用户：${userMessage}\nAI：${aiResponse}`,
          tenantAppId: this.selectedChat.tenantAppId || this.selectedChat.appId,
          chatId: this.sessionId
        },
        onMessage: (event) => {
          if (event.event === SseResponseEventEnum.answer ||
              event.event === SseResponseEventEnum.fastAnswer) {
            if (event.text && this.chatTitle === '新对话') {
              this.chatTitle = event.text.trim();
            }
          }
        }
      });

      console.log('聊天标题生成完成:', this.chatTitle);
    } catch (error) {
      console.error('生成聊天标题失败:', error);
      // 如果生成标题失败，使用默认标题
      if (this.chatTitle === '新对话') {
        this.chatTitle = userMessage.substring(0, 10) + '...';
      }
    }
  },

  /**
   * 更新聊天历史记录（按照PC端流程）
   */
  async updateChatHistory() {
    try {
      console.log('开始更新聊天历史记录...');

      const token = getToken(); // 获取动态token

    const response = await fetch('/huayun-ai/client/chat/update', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
      },
      credentials: 'include',
        body: JSON.stringify({
          id: this.sessionId,
          title: this.chatTitle || '新对话',
          chatAppId: this.selectedChat.tenantAppId || this.selectedChat.appId,
          tenantAppId: this.selectedChat.tenantAppId || this.selectedChat.appId
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('聊天历史记录更新成功:', result);
    } catch (error) {
      console.error('更新聊天历史记录失败:', error);
    }
  },

  /**
   * 使用流程数据更新聊天项详情（按照PC端流程）
   * @param {Object} flowData - 流程响应数据
   */
  async updateChatItemWithFlowData(flowData) {
    try {
      console.log('开始更新聊天项详情...');

       const token = getToken();

      if (!flowData || !this.currentResponseChatItemId) {
        console.warn('缺少必要参数，跳过聊天项更新');
        return;
      }

      // 按照PC端格式构建参数
      const payload = {
        dataId: this.currentResponseChatItemId,
        value: JSON.stringify(flowData),
        content: JSON.stringify(flowData),
        responseData: JSON.stringify(flowData)
      };

      const response = await fetch('/huayun-ai/client/chat/item/update', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
      },
        credentials: 'include',
        body: JSON.stringify(payload)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('聊天项详情更新成功:', result);
    } catch (error) {
      console.error('更新聊天项详情失败:', error);
    }
  },

  // 检查浏览器是否支持语音识别
  checkSpeechRecognitionSupport() {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (SpeechRecognition) {
      this.isSpeechSupported = true;
      this.speechRecognition = new SpeechRecognition();
      this.speechRecognition.continuous = false;
      this.speechRecognition.interimResults = true;
      this.speechRecognition.lang = 'zh-CN';

      // 语音识别结果事件
      this.speechRecognition.onresult = (event) => {
        let transcript = '';
        for (let i = event.resultIndex; i < event.results.length; i++) {
          transcript += event.results[i][0].transcript;
        }
        this.userInput = transcript;
      };

      // 语音识别结束事件
      this.speechRecognition.onend = () => {
        this.isListening = false;
      };

      // 语音识别错误事件
      this.speechRecognition.onerror = (event) => {
        console.error('语音识别错误:', event.error);
        this.isListening = false;
      };
    }
  },

  // 开始语音输入
  startSpeechInput() {
    if (!this.speechRecognition) return;

    if (!this.isListening) {
      this.isListening = true;
      this.userInput = ''; // 清空当前输入
      try {
        this.speechRecognition.start();
      } catch (error) {
        console.error('启动语音识别失败:', error);
        this.isListening = false;
      }
    } else {
      this.speechRecognition.stop();
    }
  },

  // 修改 closeAgentDialog 方法以支持终止语音识别
  async closeAgentDialog() {
    // 如果正在语音识别，停止它
    if (this.speechRecognition && this.isListening) {
      this.speechRecognition.stop();
      this.isListening = false;
    }

    // 如果有正在进行的发送请求，等待其完成
    if (this.sending && this.abortController) {
      try {
        // 等待当前请求完成，最多等待5秒
        await Promise.race([
          new Promise(resolve => setTimeout(resolve, 5000)), // 最多等待5秒
          new Promise(resolve => {
            const checkComplete = () => {
              if (!this.sending) {
                resolve();
              } else {
                setTimeout(checkComplete, 100);
              }
            };
            checkComplete();
          })
        ]);
      } catch (e) {
        console.warn('等待发送完成时出错:', e);
      }
    }

    // 重置所有状态
    this.showAgentDialog = false;
    this.selectedChat = null;
    this.messages = [];
    this.userInput = '';
    this.sessionId = null;
    this.sending = false;
    this.abortController = null;
  }
}
}
</script>

<style scoped>
.chat-list-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.chat-list-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.chat-list-header h1 {
  font-size: 18px;
  font-weight: 400;
  color: #333;
  margin: 0;
  letter-spacing: 0.5px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
  padding: 0;
  margin: 0;
  list-style: none;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background-color: #f5f5f5;
}

.chat-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
}

.chat-icon {
  font-size: 24px;
  font-style: normal; /* 添加这行 */
}

.chat-info {
  flex: 1;
  min-width: 0;
}

.chat-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.chat-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-time {
  font-size: 12px;
  color: #999;
  flex-shrink: 0;
  margin-left: 8px;
}

.chat-preview {
  font-size: 14px;
  color: #666;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-list-footer {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 4px 0;
  border-top: 1px solid #eee;
  background-color: #fff;
  flex-shrink: 0;
  position: sticky;
  bottom: 0;
  z-index: 100;
  height: 56px; /* 固定高度 */
  box-sizing: border-box;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 2px 0;
  font-style: normal;
  width: 33.333%;
}

.nav-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  color: #5f6368;
  font-size: 20px;
}

/* 对话图标 - 简洁气泡线条 */
.message-icon::before {
  content: '';
  position: absolute;
  width: 18px;
  height: 14px;
  border: 2px solid currentColor;
  border-radius: 12px 12px 12px 0;
}

.message-icon::after {
  content: '';
  position: absolute;
  width: 6px;
  height: 6px;
  border: 2px solid currentColor;
  border-top: none;
  border-left: none;
  transform: rotate(45deg);
  bottom: -2px;
  right: 2px;
}

/* 发现图标 - 简洁放大镜线条 */
.discover-icon::before {
  content: '';
  position: absolute;
  width: 12px;
  height: 12px;
  border: 2px solid currentColor;
  border-radius: 50%;
  top: 2px;
  left: 2px;
}

.discover-icon::after {
  content: '';
  position: absolute;
  width: 8px;
  height: 2px;
  background-color: currentColor;
  transform: rotate(45deg);
  bottom: 6px;
  right: 2px;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .chat-list-footer {
    padding: 4px 0;
    height: 56px;
  }

  .nav-item span {
    font-size: 12px;
  }

  .nav-icon {
    font-size: 20px;
  }
}

.nav-item span {
  font-size: 12px;
  color: #5f6368;
  margin-top: 4px;
  font-style: normal;
  font-weight: 500;
}

.nav-item.active .nav-icon,
.nav-item.active span {
  color: #4285f4;
  font-style: normal;
  font-weight: 600;
}

/* 对话框样式 */
.agent-dialog-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  box-sizing: border-box;
}

.agent-dialog-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.agent-dialog-fullscreen {
  position: absolute;
  top: 0;
  left: 0;
  background-color: white;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.dialog-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 14px 16px;
   border-bottom: 1px solid transparent; /* 改为透明 */
  box-sizing: border-box;
  /* background-color: #fff; */
  position: relative; /* 添加这行 */
}

.agent-header-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 移除头像相关样式 */
.agent-avatar-header {
  display: none; /* 隐藏头像 */
}

.agent-icon-header {
  font-size: 18px;
  color: #fff;
   font-style: normal; /* 添加这行 */
}


.dialog-header h2 {
  margin: 0;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 600; /* 保持600 */
  text-align: center;
}

.close-button {
  background: none;
  border: none;
  font-size: 22px;
  cursor: pointer;
  color: #999;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  position: absolute; /* 添加这行 */
  right: 16px; /* 添加这行 */
}

.close-button:hover {
  color: #333;
}

.dialog-content {
  flex: 1; /* 占据剩余空间 */
  overflow-y: auto; /* 允许滚动 */
  padding: 16px 20px;
  box-sizing: border-box;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #666;
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

/* 消息容器样式 */
.message-container {
  display: flex;
  gap: 8px;
  max-width: 100%;
  align-items: flex-start;
}

.message-container.bot {
  align-self: flex-start;
}

.message-container.user {
  align-self: flex-end;
  justify-content: flex-end;
  width: 100%;
}

/* 头像容器 */
.agent-avatar-container, .user-avatar-container {
  display: flex;
  align-items: flex-start;
  flex-shrink: 0;
  margin-top: 2px;
}

/* 智能体头像 */
.agent-avatar-message {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  font-style: normal; /* 添加这行 */
}

/* 用户头像 */
.user-avatar-message {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  background-color: #4285f4;
  color: white;
}

.agent-icon-message, .user-icon-message {
  font-size: 16px;
  color: #fff;
  font-style: normal; /* 添加这行 */
}

/* 消息气泡样式 */
.message-bubble.bot {
  background-color: transparent;
  border: none;
  border-radius: 0;
  padding: 10px 14px;
  max-width: 75%;
  word-wrap: break-word;
  box-sizing: border-box;
  box-shadow: none;
  position: relative;
}

/* 用户消息气泡样式 */
.message-bubble.user {
  background-color: #ffffff; /* 更浅的蓝色背景 */
  color: #333;
  border-radius: 18px; /* 圆角矩形 */
  border: none; /* 移除边框 */
  padding: 10px 14px;
  max-width: 75%;
  word-wrap: break-word;
  box-sizing: border-box;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: relative;
  width: auto;
  min-width: 60px;
  align-self: flex-end; /* 确保消息气泡靠右对齐 */
}

/* 消息内容样式 */
/* 消息内容样式 */
.message-content {
  word-wrap: break-word;
  overflow-wrap: break-word;
  font-size: 14px;
  line-height: 1.5;
  text-align: justify; /* 两端对齐 */
}

.message-content p {
  margin: 0 0 6px 0;
  text-align: justify; /* 两端对齐 */
}

.message-content p:last-child {
  margin-bottom: 0;
}

/* 消息时间 */
.message-time {
  /* font-size: 10px;
  text-align: right;
  margin-top: 4px;
  opacity: 0.7; */
  display: none;
}

.message-bubble.user .message-time {
  /* color: rgba(0, 0, 0, 0.5); */
  display: none;
}

/* 输入框样式 */
.dialog-input {
  padding: 16px 20px;
  border-top: 1px solid #eee;
  /* background-color: #f8f9fa; */
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 56px; /* 固定高度 */
}

.dialog-input input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
}

.dialog-input input:focus {
  border-color: #4285f4;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.1);
}


/* 恢复原始发送按钮样式 */
.dialog-input button {
  padding: 11px 20px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 22px;
  cursor: pointer;
  white-space: nowrap;
  font-size: 14px;
  transition: background-color 0.2s;
}

.dialog-input button:hover:not(:disabled) {
  background-color: #3367d6;
}

.dialog-input button:disabled {
  background-color: #f0f0f0;
  color: #999;
  cursor: not-allowed;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .dialog-input button {
    padding: 9px 16px;
    font-size: 13px;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .message-bubble.bot,
  .message-bubble.user {
    max-width: 85%;
  }

  .dialog-header h2 {
    font-size: 15px;
  }

  .message-content {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .message-bubble.bot,
  .message-bubble.user {
    max-width: 90%;
    padding: 9px 12px;
  }

  .dialog-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  box-sizing: border-box;
  /* background-color: #ffffff; 修改为更白的背景 */
}

  .agent-avatar-message, .user-avatar-message {
    width: 28px;
    height: 28px;
  }

  .dialog-input {
    padding: 10px 12px;
  }

  .dialog-input input {
    padding: 9px 12px;
    font-size: 13px;
  }

  .dialog-input button {
    padding: 9px 16px;
    font-size: 13px;
  }

  /* 数学公式样式 */
.math-inline {
  font-family: 'Times New Roman', serif;
  font-style: italic;
  background-color: #f8f9fa;
  padding: 2px 4px;
  border-radius: 3px;
  display: inline-block;
}

.math-block {
  font-family: 'Times New Roman', serif;
  font-style: italic;
  text-align: center;
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 5px;
  margin: 10px 0;
  overflow-x: auto;
}


/* 改善公式显示效果 */
.mjx-chtml {
  outline: 0;
}

.MathJax_CHTML {
  font-size: 100%;
}

/* 改进标题样式 */
.message-content h1,
.message-content h2,
.message-content h3,
.message-content h4,
.message-content h5,
.message-content h6 {
  margin: 12px 0 8px 0;
  font-weight: 600;
  color: inherit;
}

.message-content h1 {
  font-size: 1.6em;
  border-bottom: 2px solid #e0e0e0;
  padding-bottom: 5px;
}

.message-content h2 {
  font-size: 1.4em;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 4px;
}

.message-content h3 {
  font-size: 1.2em;
  border-bottom: 1px dashed #e0e0e0;
  padding-bottom: 3px;
}

.message-content h4 {
  font-size: 1.1em;
}

.message-content h5 {
  font-size: 1em;
}

.message-content h6 {
  font-size: 0.9em;
}

/* 链接样式 */
.message-content a {
  color: #4285f4;
  text-decoration: none;
  border-bottom: 1px solid #4285f4;
}

.message-content a:hover {
  color: #3367d6;
  border-bottom: 1px solid #3367d6;
}

/* 在样式部分添加语音输入按钮样式 */
.speech-button {
  background-color: transparent !important;
  border: none;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 0;
  position: relative;
  border-radius: 50%;
  outline: none;
}

.speech-button:hover:not(:disabled) {
  background-color: #f5f5f5 !important;
}

.speech-button:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.speech-button.listening {
  background-color: #e3f2fd !important;
}

.mic-icon {
  position: relative;
  width: 16px;
  height: 16px;
  border: 2px solid #5f6368;
  border-radius: 8px 8px 2px 2px;
  transition: all 0.2s ease;
}

.mic-icon:before {
  content: '';
  position: absolute;
  top: -6px;
  left: 50%;
  transform: translateX(-50%);
  width: 8px;
  height: 8px;
  border: 2px solid #5f6368;
  border-radius: 50%;
  background-color: white;
}

.mic-icon:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 2px;
  height: 10px;
  background-color: #5f6368;
}

.speech-button:hover:not(:disabled) .mic-icon,
.speech-button:hover:not(:disabled) .mic-icon:before,
.speech-button:hover:not(:disabled) .mic-icon:after {
  border-color: #4285f4;
  background-color: white;
  color: #4285f4;
}

.speech-button.listening .mic-icon,
.speech-button.listening .mic-icon:before,
.speech-button.listening .mic-icon:after {
  border-color: #4285f4;
  background-color: white;
  color: #4285f4;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}

/* 移动端适配 */
@media (max-width: 480px) {
  .speech-button {
    width: 36px;
    height: 36px;
  }

  .mic-icon {
    width: 14px;
    height: 14px;
  }

  .mic-icon:before {
    width: 7px;
    height: 7px;
    top: -5px;
  }

  .mic-icon:after {
    height: 8px;
    bottom: -8px;
  }
}

/* 用户选择界面样式 */
.user-select-container {
  background-color: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 18px;
  border-top-left-radius: 4px;
  padding: 16px;
  margin: 10px 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.select-description {
  font-size: 14px;
  color: #333;
  margin-bottom: 12px;
  font-weight: 500;
}

.select-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.select-option-button {
  padding: 10px 16px;
  background-color: #f1f3f4;
  color: #333;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  text-align: left;
  transition: all 0.2s ease;
}

.select-option-button:hover {
  background-color: #e8eaed;
  border-color: #dadce0;
}

/* 添加嵌入式用户选择界面样式 */
.embedded-user-select {
  background-color: #f8f9fa;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  padding: 12px;
  margin-top: 10px;
}

.embedded-user-select .select-description {
  font-size: 13px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.embedded-user-select .select-options {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.embedded-user-select .select-option-button {
  padding: 8px 12px;
  background-color: #ffffff;
  color: #333;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  font-size: 13px;
  text-align: left;
  transition: all 0.2s ease;
}

.embedded-user-select .select-option-button:hover {
  background-color: #f5f5f5;
  border-color: #bdbdbd;
}

.embedded-user-select .select-option-button.selected {
  background-color: #e3f2fd;
  border-color: #bbdefb;
  font-weight: 500;
}

/* 改进Markdown内容样式 */
.message-content h1,
.message-content h2,
.message-content h3 {
  margin: 12px 0 8px 0;
  font-weight: 600;
  color: inherit;
}

.message-content h1 {
  font-size: 1.4em;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 4px;
}

.message-content h2 {
  font-size: 1.3em;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 3px;
}

.message-content h3 {
  font-size: 1.2em;
}

.message-content strong {
  font-weight: 600;
}

.message-content em {
  font-style: italic;
}

.message-content code {
  background-color: #e0e0e0;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.message-content blockquote {
  border-left: 3px solid #4285f4;
  padding-left: 12px;
  margin: 8px 0;
  color: #666;
  text-align: left; /* 确保引用块左对齐 */
}

.message-content hr {
  border: none;
  border-top: 1px solid #e0e0e0;
  margin: 12px 0;
}

/* 首页图标 - 简洁房屋线条 */
.home-icon::before {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-bottom: 8px solid currentColor;
  top: -4px;
}

.home-icon::after {
  content: '';
  position: absolute;
  width: 16px;
  height: 12px;
  border: 2px solid currentColor;
  top: 4px;
}


}
</style>
